package gorouting

import (
	"fmt"
	"sync"
)

type myPool struct {
	maxWorkers int
	taskQueue  chan func()
	stopChan   chan struct{}
	wg         sync.WaitGroup
}

// MyNewPool 创建协程池
func MyNewPool(maxWorkers, queueSize int) *myPool {
	return &myPool{
		maxWorkers: maxWorkers,
		taskQueue:  make(chan func(), queueSize),
		stopChan:   make(chan struct{}),
		wg:         sync.WaitGroup{},
	}
}

// MyStart 启动任务
func (mp *myPool) MyStart() {
	for i := 0; i < mp.maxWorkers; i++ {
		mp.wg.Add(1)
		go mp.worker()
	}
	return
}

func (mp *myPool) worker() {
	defer mp.wg.Done()
	for {
		select {
		case task := <-mp.taskQueue:
			task()
		case <-mp.stopChan:
			return
		}
	}
}

// MySubmit 注册任务
func (mp *myPool) MySubmit(invokeFUnc func()) {
	select {
	case mp.taskQueue <- invokeFUnc:
	case <-mp.stopChan:
		fmt.Println("Pool is closed, task rejected")
	}
}

func (mp *myPool) Shutdown() {
	close(mp.stopChan)
	mp.wg.Wait()
	close(mp.taskQueue)
}

// 示例用法
//func main() {
//	pool := NewPool(3, 10) // 3个协程，10个任务队列
//	pool.Start()
//
//	// 提交15个任务
//	for i := 0; i < 15; i++ {
//		//id := i
//		pool.Submit(func() {
//			time.Sleep(500 * time.Millisecond)
//			//fmt.Printf("Task %d done by %d\n", id, <-getGoroutineID())
//		})
//	}
//
//	time.Sleep(3 * time.Second)
//	pool.Shutdown()
//	fmt.Println("Pool gracefully stopped")
//}
